/**
 * @file 学部看板报表
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-03-18
 */
import React, {useState, useEffect, useRef, useMemo} from 'react';
import {Card, Row, Col} from 'antd';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import ColorTable from '~/page/FineBi/common/ColorTable';
import {querySelectOptions} from '~/service/refundReport';
import {convertSearcherParams, toLine} from '~/page/FineBi/utils/convert';
import {userRoundIdx, initUserRoundIdx} from '~/utils/const';
import {getDefaultDimension, initialValues, searchForm} from './config';

const SELECT_UNIT_ID = 'DepartmentDimensionReport_PartThree_select_1';

export default function TargetAndSynthesisRate(props) {
    const initDemenstion = useMemo(() =>
        getDefaultDimension(SELECT_UNIT_ID, initialValues).concat(props.initPropDimensionAndValues), []);
    const [selectOptions, setSelectOptions] = useState({});
    // 共同查询条件
    const [dimensionAndValues, setDimensionAndValues] = useState(initDemenstion);
    const [searchValues, setSearchValues] = useState(initDemenstion);
    const formRef = useRef();

    useEffect(() => {
        const findItem = initDemenstion.find(item => item.dimensionName === userRoundIdx);
        findItem.value = [props.userRoundValue];

        setDimensionAndValues([...initDemenstion]);

        formRef.current.formFields.resetFields();
    }, [props.userRoundValue]);

    const handleOk = fieldsValue => {
        const params = convertSearcherParams(fieldsValue, SELECT_UNIT_ID);
        setDimensionAndValues([...params, {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}]);
    };

    const handleReset = e => {
        const params = getDefaultDimension(SELECT_UNIT_ID, initialValues);
        setDimensionAndValues([...params, {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}]);
    };

    // 选项查询
    const handleFetchOptions = options => {
        const {key, searchKey, pager, isGetingMore, options: curOptions, fieldsValue} = options;
        let permissions = searchForm.map(item => ({
            dimensionId: `${SELECT_UNIT_ID}_${toLine(item.key)}`,
            dimensionName: toLine(item.key),
            filterItems: Array.isArray(fieldsValue[item.key])
                ? fieldsValue[item.key]
                : fieldsValue[item.key] == null
                    ? []
                    : [fieldsValue[item.key]]
        }));

        permissions = permissions.filter(item => (item.filterItems?.length && item.dimensionName !== userRoundIdx));
        permissions.push({...props.initPropDimensionAndValues[0], value: [props.userRoundValue]});

        const params = {
            pager,
            dimensionId: `${SELECT_UNIT_ID}${toLine(key)}`,
            dimensionName: toLine(key),
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        const filterValue = {...itemKeyValue};
        let dimensionValues = [...searchValues];
        for (const i in filterValue) {
            filterValue[i] = filterValue[i].filter(ele => ele !== '全部');
            formRef.current.formFields.setFieldsValue({
                [i]: filterValue[i]
            });
            dimensionValues = dimensionValues.map(ele => {
                if (ele.dimensionId === `${SELECT_UNIT_ID}_${toLine(i)}`) {
                    ele.value = filterValue[i];
                }
                return ele;
            });
        }
        setSearchValues(dimensionValues);
    };

    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchForm}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                    onItemChange={handleItemChange}
                    ref={formRef}
                />
            </Card>
            <Row>
                <Col span={24}>
                    <ColorTable
                        dimensionAndValues={dimensionAndValues}
                        unitId="DepartmentDimensionReport_PartThree_excel_1"
                        dId="DepartmentDimensionReport_PartThree_1"
                    />
                </Col>
                <Col span={24}>
                    <ColorTable
                        dimensionAndValues={dimensionAndValues}
                        unitId="DepartmentDimensionReport_PartFour_excel_1"
                        dId="DepartmentDimensionReport_PartFour_1"
                    />
                </Col>
            </Row>
        </div>
    );
}
